﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Windows.Forms;

//Sybase:
using Sybase.Mobile;
using Sybase.Persistence;
using Sybase.Collections;

using FieldServices_01;
using iAnywhere.Data.UltraLite;
using iAnywhere.UltraLite.Collations;

namespace FieldServices
{
    class Common
    {
        #region Common .Net
        public static string CurrentFolder
        {
            get
            {
                string folderName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
                return folderName;
            }
        }
        public static DataSet dsItems
        {
            get
            {
                String configPath = Path.Combine(Common.CurrentFolder, "WorkingItem.xml");
                DataSet ds = new DataSet();
                ds.ReadXml(configPath);
                return ds;
            }
        }

        public static bool bchoise { get; set; }

        #endregion

        #region Common Sybase
        private static frmLogin frmlog = new frmLogin();

        public class MyCallbackHandler : Sybase.Persistence.DefaultCallbackHandler
        {
            public static TextBox txtStt = new TextBox();

            private void invokeDelegate(long i)
            {
                //Customers f = Program.getForm1();
                //f.Invoke(f.m_refreshItem, new Object[] { i });
            }

            public override SynchronizationAction OnSynchronize(GenericList<ISynchronizationGroup> groups, SynchronizationContext context)
            {
                return SynchronizationAction.CONTINUE;

                if (context.Status == SynchronizationStatus.FINISHING || context.Status == SynchronizationStatus.ASYNC_REPLAY_UPLOADED)
                {
                    Query query = new Query();
                    GenericList<IChangeLog> changeLogs = FieldServices_01DB.GetChangeLogs(query);
                    foreach (IChangeLog changeLog in changeLogs)
                    {
                        if (changeLog.EntityType == EntityType.MboLogin)
                        {
                            invokeDelegate(changeLog.SurrogateKey);
                        }
                    }
                }

                return SynchronizationAction.CONTINUE;
            }
        }

        //public static List<MboLogin> logins = new List<MboLogin>();
        public static MboLogin login { get; set; }
        public static List<MboError> errors { get; set; }
        public static List<MboWorkitems> workItems { get; set; }
        public static List<MboOperations> operations { get; set; }
        public static MboNotif notifications { get; set; }
        public static List<MboHistory> history { get; set; }
        public static List<MboComponent> components { get; set; }
        public static List<ConfInput> conf { get; set; }
        private static PersonalizationParameters pp = new PersonalizationParameters();
        #endregion

        #region Default value

        // [DllImport("ulnet12.dl")]
        private const String USERNAME = "supAdmin";
        private const String PASSWORD = "sapadmin1";
        private const String HOST = "10.15.160.36";
        private const int PORT = 5001;
        private const int TIMEOUT = 600;

        private System.Collections.Generic.Dictionary<string, long> IdToSK = new System.Collections.Generic.Dictionary<string, long>();
        internal static System.Collections.Generic.Dictionary<long, int> SKToIndex = new System.Collections.Generic.Dictionary<long, int>();

        #endregion

        //Sychronize with package on SCC
        private static void Sync()
        {
            if (Sybase.Mobile.Application.GetInstance().RegistrationStatus != RegistrationStatus.REGISTERED &&
                Sybase.Mobile.Application.GetInstance().ConnectionStatus != ConnectionStatus.CONNECTED)
            {
                throw new SynchronizeException("Application is not initialized!");
            }
            else
            {
                //Sync data
                if (!FieldServices_01DB.IsSynchronized("default"))
                {

                    FieldServices_01DB.DisableChangeLog();
                    frmlog.AddString("Package synchronizing ...");
                    frmlog.Show();
                    FieldServices_01DB.Synchronize(); // Initial Synchronize

                    ISynchronizationGroup sg = FieldServices_01DB.GetSynchronizationGroup("default");

                    sg.EnableSIS = true;
                    sg.Save();
                    FieldServices_01DB.Synchronize();
                    frmlog.AddString("Package synchronized");
                    frmlog.Show();
                }
            }

        }

        //Register application
        public static void Register(TextBox stt)
        {
            //Set application details
            Sybase.Mobile.Application app = Sybase.Mobile.Application.GetInstance();
            app.ApplicationIdentifier = "FieldServices_01";

            MyCallbackHandler.txtStt = stt;
            FieldServices_01DB.RegisterCallbackHandler(new MyCallbackHandler());

            FieldServices_01DB.SetApplication(app);
            FieldServices_01DB.GetSynchronizationProfile().ServerName = HOST;

            //Set authentication credentials
            ConnectionProperties connProps = app.ConnectionProperties;
            LoginCredentials loginCredentials = new LoginCredentials(USERNAME, PASSWORD);

            connProps.LoginCredentials = loginCredentials;
            connProps.ServerName = HOST;
            connProps.PortNumber = PORT;

            //Register connection
            if (app.RegistrationStatus != RegistrationStatus.REGISTERED)
            {
                frmlog.AddString("Application registering ... ");
                frmlog.Show();
                app.RegisterApplication(TIMEOUT);
                frmlog.AddString("Application registered");
                frmlog.Show();
            }
            else
            {
                frmlog.AddString("Connecting to server ...");
                frmlog.Show();
                app.StartConnection(TIMEOUT);
                frmlog.AddString("Connected to server");
                frmlog.Show();
            }

            Common.Sync();

            FieldServices_01DB.EnableChangeLog();
        }

        //Login
        public static MboLogin _MboLogin(string uname, string pwd)
        {
            Sync();
            
            pp.UnamePK = uname;
            pp.PwdPK = pwd;
            pp.Save();

            FieldServices_01DB.Synchronize();
            List<MboLogin> logins = MboLogin.FindAll();
            
            foreach (MboLogin lg in logins)
            {
                login = lg;
            }
            return (login);
        }

        //Workitems
        public static void _Workitems()
        {
            Sync();
            pp.PersonelPK = login.PERSNO;
            pp.Save();

            FieldServices_01DB.Synchronize();

            errors = MboError.FindAll();
            workItems = MboWorkitems.FindAll();
            
        }

        //Operations
        public static void _Operations(string oderId)
        {
            operations = MboOperations.FindByOder(oderId);
        }

        //Components
        public static void _Component(string oderId)
        {
            components = MboComponent.FindByOder(oderId);
        }

        //History
        public static void _History(string equip)
        {
            history = MboHistory.FindByEquip(equip);
        }

        //Notifications
        public static void _Notifications(string notif)
        {
            Sync();
            pp.NotifPK = notif;
            pp.Save();

            FieldServices_01DB.Synchronize();

            notifications = MboNotif.FindByNotif(notif);

        }

        //Confirmations
        public static void _Confirm(
            string oderId,
            string Operation,
            string personel,
            string plant,
            string workct  )
        {
            ConfInput cn = new ConfInput();
            cn.ORDERID = oderId;
            cn.OPERATION = Operation;
            cn.PERS_NO = personel;
            cn.PLANT = plant;
            cn.WORK_CNTR = workct;

            conf.Add(cn);
            
            MboConfConfOpOperation.SubmitPendingOperations();
            ISynchronizationGroup sg = FieldServices_01DB.GetSynchronizationGroup("default");
            GenericList<ISynchronizationGroup> syncGroups = new GenericList<ISynchronizationGroup>();
            syncGroups.Add(sg);
            FieldServices_01DB.BeginSynchronize(syncGroups, "");
        }   

    }
}
